package info

import (
	"encoding/json"
	"log"
	"os"
	"path/filepath"
	"time"

	"gitee.com/chuanjinge/go-container/config"
	"gitee.com/chuanjinge/go-container/container/containerconfig"
)

type ContainerInfo struct {
	ID                     string
	Name                   string
	State                  ContainerInfoState
	Config                 ContainerInfoConfig
	Created                time.Time
	Command                string
	LogPath                string
	RestartCount           int
	HasBeenManuallyStopped bool
	MountPoints            map[string]*ContainerMountPoint
	NetworkSettings        ContainerInfoNetwork
}

type ContainerInfoState struct {
	Running     bool
	Paused      bool
	Restarting  bool
	Pid         int
	ExitCode    int
	StartedAt   time.Time
	FinisededAt time.Time
}

type ContainerInfoConfig struct {
	Hostname  string
	OpenStdin bool
	Image     string
	Tty       bool
}

type ContainerInfoNetwork struct {
	Bridge   string
	Networks map[string]ContainerInfoNetworkItem // 网络名称=>网络信息
	Ports    map[int16]int16                     // 端口映射  容器端口:宿主机端口
}

type ContainerInfoNetworkItem struct {
	MacAddress  string
	Gateway     string
	IPAddress   string
	IPPrefixLen int
}

type ContainerMountPoint struct {
	Source      string
	Destination string
	RW          bool
	Name        string
	Driver      string
	Type        string
	Propagation string
}

// 根据给定的containerId构造containerInfo
func GetContainerInfoByContainerId(containerId string) (*ContainerInfo, error) {
	// 去container目录中找到该文件夹，读取，构造
	configFilePath := filepath.Join(config.GlobalConfig().ContainerPath, containerId, containerconfig.CONFIG_V2_LOG)
	return ReadConfigV2JsonAndUnmarshal(configFilePath)
}

func ReadConfigV2JsonAndUnmarshal(configFilePath string) (*ContainerInfo, error) {
	content, err := os.ReadFile(configFilePath)
	if err != nil {
		log.Printf("[getContainerInfo]READ file %s error: %v", configFilePath, err)
		return nil, err
	}

	info := new(ContainerInfo)
	if err = json.Unmarshal(content, info); err != nil {
		log.Printf("[getContainerInfo]json unmarshal error %v", err)
		return nil, err
	}

	return info, nil
}
